import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { OssService } from 'src/oss/oss.service';
import { MongoService } from '../mongo/mongo.service';
import { GetListDto } from './dto/music.dto';
import { decrypt } from 'ncm-decrypt';
@Injectable()
export class MusicService {
  constructor(
    private ossService: OssService,
    private mongoService: MongoService,
  ) {}
  async upLoad(file: Express.Multer.File) {
    try {
      if (file.originalname.endsWith('.ncm')) {
        const res = await decrypt(file.buffer.buffer, file.originalname);
        file.buffer = Buffer.from(res.buffer);
        file.originalname = file.originalname.replace('.ncm', `.${res.ext}`);
      }
      await this.ossService.client.head(file.originalname);
      throw new HttpException(
        file.originalname + '文件已存在',
        HttpStatus.BAD_REQUEST,
      );
    } catch (error) {
      if (error instanceof HttpException) {
        throw error;
      } else {
        const musicResponse = await this.ossService.client.put(
          file.originalname,
          file.buffer,
        );
        await this.mongoService.addMusic(musicResponse);
        return '上传成功';
      }
    }
  }
  getList(query: GetListDto) {
    return this.mongoService.getList(query);
  }
  search(keywords: string) {
    return this.mongoService.search(keywords);
  }
}
